//
//  OYTextView+Extension.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/14.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import Foundation

extension OYTextView {
    
    
    /// 将表情插入textView中以富文本进行显示
    ///
    /// - Parameter emotionModel: 选中表情的model
    func insertEmotion(emotionModel:OYEmotionModel) {
        // 将选中表情添加至textView上
        // 判断表情是图片表情还是emoji表情
        if  emotionModel.type == "0" {
            // 图片表情
            // 创建一个存储attributeString的变量
            let emotionAttributeStr = NSMutableAttributedString(attributedString:self.attributedText)
            // 获取表情的UIimage对象
            let emotionImage = UIImage(named: emotionModel.path!)
            // 根据UIIMage对象拿到图片附件
            let attachment = OYEmotionAttachment()
            // MARK: -将model传递给自定义的attachMent对象
            attachment.emotionModel = emotionModel
            attachment.image = emotionImage
            // 设置表情与文字大小一致
            let textLineHight = self.font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: textLineHight, height: textLineHight)
            // 根据附件创建富文本
            let attributeEmotionText = NSAttributedString(attachment: attachment)
            
            // 将富文本添加至富文本字符串
            //            emotionAttributeStr.append(attributeEmotionText)
            // MARK: -设置当光标不在最后的时候也可以插入表情
            var range = self.selectedRange
            emotionAttributeStr.replaceCharacters(in: range, with: attributeEmotionText)
            
            // MARK: -设置富文本的字体大小！
            emotionAttributeStr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, emotionAttributeStr.length))
            
            // 将富文本字符串添加在textView上
            self.attributedText = emotionAttributeStr
            
            // 设置当前光标的位置
            range.location += 1
            range.length = 0
            self.selectedRange = range
            
            // 当有表情输入的时候，调用代理方法设置占位文字取消
            self.delegate?.textViewDidChange!(self)
            
        }else {
            // emoji表情
            let emojiStr = (emotionModel.code! as NSString).emoji()
            //            // 根据string创建富文本
            //            let attributeEmojiText = NSAttributedString(string: emojiStr!)
            //            // 将富文本添加至富文本字符串
            //            emotionAttributeStr.append(attributeEmojiText)
            self.insertText(emojiStr!)
            
        }
    }
}
